<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Quyen extends CI_Controller
{

	public	function __construct()
	{
		parent::__construct();
		$this->load->library('pagination');
		if($this->session->userdata('user_id')){
			$this->load->helper("html");
			$this->load->model("tailieus");
			$this->load->model("giaobans");
			$this->load->model("users");
			$this->load->model("lich");
			$this->load->model("log_model");
			$this->load->model("quyen_model");
			date_default_timezone_set('Asia/Ho_Chi_Minh');
		}
		else{
			redirect('login');
		}
	}

	public function index($msg=null,$parameter=null){
		$data['menu'] = 'user_'.$msg;
		$data['list_tailieu'] = $this->tailieus->listTailieu();
		$data['list_giaoban'] = $this->giaobans->listGiaoban();
		/////////////
		$data['menu_tin'] = $this->giaobans->listGiaoban();
		$list = array();
		foreach ($data['menu_tin'] as $l){		//sap xep nhom danh sach theo giao ban cha
			if($l->id_type_giaoban != 9)
				$list[$l->cha_giaoban][] = $l;
		}
		
		$data['multi_menu_tin'] = $this->giaobans->multiGiaoban($list,0);						
		////////////
		$data['list_lich'] = $this->lich->listLich();
		$this->load->view('header_block_v1',$data);
		$this->load->view('content_sidebar_block',$data);
		switch ($msg){
			case 'quyen':
				$this->viewQuyen();
				break;
			case 'viewAdd':
				$this->viewAddQuyen();
				break;
			case 'viewEdit':
				$this->viewEditQuyen($parameter);
				break;
			default:
				$this->viewQuyen();
				break;
		}
		$this->load->view('footer_block');
	}
	private function viewQuyen(){
		$this->load->model('quyen_model');
		$data['quyen'] = $this->quyen_model->listQuyen();
		$this->load->view("quyen/viewQuyen",$data);
	}
	private function viewAddQuyen(){
		$this->load->view('quyen/viewAddQuyen');
	}
	private function viewEditQuyen($id_quyen){
		$this->load->model('quyen_model');
		$data['quyen'] = $this->quyen_model->getQuyen($id_quyen);
		switch($data['quyen']->loai_quyen){
			case 0:
				$listLich = $this->lich->listLich();
				foreach($listLich as $lich){
					$dropdown_menulich[$lich->id_danhsachlich] = $lich->ten_lich;
				}
				$data['dropdown'] = $dropdown_menulich;
				break;
			case 1:
				$listGiaoban = $this->giaobans->listGiaoban();
				foreach($listGiaoban as $giaoban){
					$dropdown_menutin[$giaoban->id_type_giaoban] = $giaoban->menu_name_giaoban;
				}
				$data['dropdown'] = $dropdown_menutin;
				break;
			case 2:
				$listTailieu = $this->tailieus->listTailieu();
				foreach($listTailieu as $tailieu){
					$dropdown_menutailieu[$tailieu->id_type_tailieu_vtv4] = $tailieu->ten_type_tailieucol_vtv4;
				}
				$data['dropdown'] = $dropdown_menutailieu;
				break;
			default:break;
		}
		//print_r($data);
		$this->load->view('quyen/viewEditQuyen',$data);
	}
	public function loadajax(){
		$type_quyen = $this->input->post('type_quyen');
		switch($type_quyen){
			case 0:
				$this->loadMenuLich();
				break;
			case 1:
				$this->loadMenuTin();
				break;
			case 2:
				$this->loadMenuTailieu();
				break;
			default:
				echo "Chưa chọn loại quyền";
				break;
		}
	}
	private function loadMenuTin(){
		$dropdown_menutin = array();
		$listGiaoban = $this->giaobans->listGiaoban();
		foreach($listGiaoban as $giaoban){
			$dropdown_menutin[$giaoban->id_type_giaoban] = $giaoban->menu_name_giaoban;
		}
		echo form_label('Giới hạn menu tin',"",array('class'=>'stylelabel'))."</br>".form_dropdown('link_quyen',$dropdown_menutin)."</br>";
	}
	private function loadMenuLich(){
		$dropdown_menulich = array();
		$listLich = $this->lich->listLich();
		foreach($listLich as $lich){
			$dropdown_menulich[$lich->id_danhsachlich] = $lich->ten_lich;
		}
		echo form_label('Giới hạn lịch làm việc',"",array('class'=>'stylelabel'))."</br>".form_dropdown('link_quyen',$dropdown_menulich)."</br>";
	}
	private function loadMenuTailieu(){
		$dropdown_menutailieu = array();
		$listTailieu = $this->tailieus->listTailieu();
		foreach($listTailieu as $tailieu){
			$dropdown_menutailieu[$tailieu->id_type_tailieu_vtv4] = $tailieu->ten_type_tailieucol_vtv4;
		}
		echo form_label('Giới hạn tài liệu',"",array('class'=>'stylelabel'))."</br>".form_dropdown('link_quyen',$dropdown_menutailieu)."</br>";
	}

	public function addQuyen(){
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		//dieu kien form
		$this->form_validation->set_rules('ten_quyen', 'Tên quyền', 'trim|xss_clean|required|min_length[5]');
		if ($this->form_validation->run() == FALSE){
			$this->index('viewAdd');
		}
		else{
			$url = site_url('quyen');
			$data["ten_quyen"] = $this->input->post("ten_quyen");
			$data["loai_quyen"] = $this->input->post("loai_quyen");
			if($data["loai_quyen"] == 4){
				echo "<script>alert('Bạn chưa chọn quyền');</script>";
				$this->index('viewAdd');
			}
			else{
				$data["link_quyen"] = $this->input->post("link_quyen");
				$this->load->model("quyen_model");
					
				if($this->quyen_model->addQuyen($data)){
					//if($this->log_model->saveLog(3,null,null,"Tin ".$name_giaoban." - ".$data["tieude_giaoban"]))
					echo "<script>alert('Thêm thành công');	window.location='".$url."'; </script>";
				}
				else
					echo "<script>alert('Lỗi: Không insert được!');	window.location='".$url."'; </script>";
			}
		}
	}
	public function editQuyen($id_quyen){
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		//dieu kien form
		$this->form_validation->set_rules('ten_quyen', 'Tên quyền', 'trim|xss_clean|required|min_length[5]');
		if ($this->form_validation->run() == FALSE){
			$this->index('viewEdit');
		}
		else{
			$url = site_url('quyen');
			$data["ten_quyen"] = $this->input->post("ten_quyen");
			$data["loai_quyen"] = $this->input->post("loai_quyen");
			if($data["loai_quyen"] == 4){
				echo "<script>alert('Bạn chưa chọn quyền');</script>";
				$this->index('viewAdd');
			}
			else{
				$data["link_quyen"] = $this->input->post("link_quyen");
				$this->load->model("quyen_model");
					
				if($this->quyen_model->editQuyen($data,$id_quyen)){
					//if($this->log_model->saveLog(3,null,null,"Tin ".$name_giaoban." - ".$data["tieude_giaoban"]))
					echo "<script>alert('Sửa thành công');	window.location='".$url."'; </script>";
				}
				else
					echo "<script>alert('Lỗi: Không update được!');	window.location='".$url."'; </script>";
			}
		}
	}

	public function showQuyenDataTable(){
			
		$aColumns = array('ten_quyen', 'loai_quyen', 'gioihan_truycap', 'xoa');
		$_aColumns = array( 'A.ten_quyen', 'A.loai_quyen', 'ten_link');
		/* Indexed column (used for fast and accurate table cardinality) */
		$sIndexColumn = "id_quyen";

		// DB table to use
		$sTable = 'vtv4_quyen';

		$iDisplayStart = $this->input->get_post('iDisplayStart', true);
		$iDisplayLength = $this->input->get_post('iDisplayLength', true);
		$iSortCol_0 = $this->input->get_post('iSortCol_0', true);
		$iSortingCols = $this->input->get_post('iSortingCols', true);
		$sSearch = $this->input->get_post('sSearch', true);
		$sEcho = $this->input->get_post('sEcho', true);

		// Paging
		if(isset($iDisplayStart) && $iDisplayLength != '-1' && $iDisplayLength != '0')
		{
			$this->db->limit($this->db->escape_str($iDisplayLength), $this->db->escape_str($iDisplayStart));
		}
		// Ordering
		if(isset($iSortCol_0))
		{
			for($i=0; $i<intval($iSortingCols); $i++)
			{
				$iSortCol = $this->input->get_post('iSortCol_'.$i, true);
				$bSortable = $this->input->get_post('bSortable_'.intval($iSortCol), true);
				$sSortDir = $this->input->get_post('sSortDir_'.$i, true);

				if($bSortable == 'true')
				{
					$this->db->order_by($_aColumns[intval($this->db->escape_str($iSortCol))], $this->db->escape_str($sSortDir));
				}
			}
		}

		if(isset($sSearch) && !empty($sSearch))
		{
			for($i=0; $i<count($_aColumns); $i++)
			{
				$bSearchable = $this->input->get_post('bSearchable_'.$i, true);

				// Individual column filtering
				if(isset($bSearchable) && $bSearchable == 'true')
				{
					$this->db->or_like($_aColumns[$i], $this->db->escape_like_str($sSearch));
				}
			}
		}
		// Select Data
		$this->db->select('A.ten_quyen, A.id_quyen, A.loai_quyen,
				case A.loai_quyen 
				when 0 then B.ten_lich
				when 1 then C.menu_name_giaoban
				when 2 then D.ten_type_tailieucol_vtv4
				end as ten_link', false);
		//$this->db->select('SQL_CALC_FOUND_ROWS '.str_replace(' , ', ' ', implode(', ', $_aColumns)), false);
		$this->db->from('vtv4_quyen A');
		$this->db->join('vtv4_danhsachlich B', 'B.id_danhsachlich = A.link_quyen','left');
		$this->db->join('vtv4_type_giaoban C', 'C.id_type_giaoban = A.link_quyen','left');
		$this->db->join('vtv4_type_tailieu D', 'D.id_type_tailieu_vtv4 = A.link_quyen','left');

		$rResult = $this->db->get();
		//$rResult = $this->db->get($sTable);
		// Data set length after filtering
		$this->db->select('FOUND_ROWS() AS found_rows');
		$iFilteredTotal = $this->db->get()->row()->found_rows;
		// Total data set length
		$iTotal = $this->db->count_all($sTable);
		// Output
		$output = array(
				'sEcho' => intval($sEcho),
				'iTotalRecords' => $iTotal,
				'iTotalDisplayRecords' => $iFilteredTotal,
				'aaData' => array()
		);

		$result = $rResult->result_array();
		/* echo "<pre>";
		print_r($result);
		echo "</pre>"; */
		foreach($result as $log){
			$row = array();
			for ( $i=0 ; $i<count($aColumns) ; $i++ ){
				switch($aColumns[$i]){
					case "gioihan_truycap":
						$row[] = $log['ten_link'];
						break;
					case "loai_quyen":
						$row[] = $log[$aColumns[$i]] == 0 ? "Chỉnh sửa lịch": ($log[$aColumns[$i]] == 1 ? "Chỉnh sửa tin": "Chỉnh sửa công văn");
						break;
					case "xoa":
						$row[] = "<a href='".site_url('quyen/del/'.$log['id_quyen'])."'>Xóa</a>";
						break;
					default:
						$row[] = "<a href='".site_url('quyen/viewEdit/'.$log['id_quyen'])."'>".$log[$aColumns[$i]]."</a>";
						break;
				}				
			}
			$output['aaData'][] = $row;
		}
		/*echo "<pre>";
		 print_r($output);
		echo "</pre>";*/
		echo json_encode( $output );
	}
	public function delQuyen($id_quyen){		
		if($this->quyen_model->delQuyen($id_quyen)){
			$url = site_url('quyen');
			echo "<script>alert('Xóa thành công');	window.location='".$url."'; </script>";
		}
		else{
			echo "Lỗi: Không delete được!";
		}
	}
}